//
//  MCNewMarketingViewController.swift
//  StoreManage
//
//  Created by MC on 2018/6/20.
//  Copyright © 2018年 MC. All rights reserved.
//

import UIKit

import UIKit

class MCNewMarketingViewController: MCViewController {
    
    public var activityId = 0    // 更新活动信息，需要这个字段
    
    public var dataDict = NSDictionary()  // 
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        managerClosure()
        
        sendNetworking()
    }
    
    // MARK: - System Delegate
    
    // MARK: - Custom Delegate
    
    // MARK: - Closure
    func managerClosure() {

    }
    // MARK: - Action
    @objc override func leftItemClicked() {
        MCAlterController_twoOptions(vc: self, message: "是否放弃当前编辑的内容", confirm: {
            self.navigationController?.popViewController(animated: true)
        }) { }
    }
    
    @objc func rightItemClicked() {
        
        let titleStr = headView.writeView.titleTextView.textView.text ?? ""
        let remark = headView.writeView.detailTextView.textView.text ?? ""
        
        
        if titleStr.isEmpty {
            MCHUD_text(message: "请填写活动标题", view: self.view, delay: 1.2)
            return
        }
        
        if remark.isEmpty {
            MCHUD_text(message: "请填写活动内容", view: self.view, delay: 1.2)
            return
        }
        
        if !headView.timeView.activityBeginTimeView.contentButton.isSelected {
            MCHUD_text(message: "请选择活动开始时间", view: self.view, delay: 1.2)
            return
        }
        
        if !headView.timeView.activityEndTimeView.contentButton.isSelected {
            MCHUD_text(message: "请选择活动结束时间", view: self.view, delay: 1.2)
            return
        }
        
        if !headView.timeView.pickUpBeginTimeView.contentButton.isSelected {
            MCHUD_text(message: "请选择提货开始时间", view: self.view, delay: 1.2)
            return
        }
        
        if !headView.timeView.pickUpEndTimeView.contentButton.isSelected {
            MCHUD_text(message: "请选择提货结束时间", view: self.view, delay: 1.2)
            return
        }

        if !headView.statusView.statusView.contentButton.isSelected {
            MCHUD_text(message: "请选择活动状态", view: self.view, delay: 1.2)
            return
        }
        
        if dataArrayM.count == 0 {
            MCHUD_text(message: "请选择活动商品", view: self.view, delay: 1.2)
            return
        }
        
        let startTime = headView.timeView.activityBeginTimeView.contentButton.currentTitle ?? ""
        let endTime = headView.timeView.activityEndTimeView.contentButton.currentTitle ?? ""
        
        let pickUpStartTime = headView.timeView.pickUpBeginTimeView.contentButton.currentTitle ?? ""
        let pickUpEndTime = headView.timeView.pickUpEndTimeView.contentButton.currentTitle ?? ""
       
        
        var status = 1
        let statusStr = headView.statusView.statusView.contentButton.currentTitle ?? ""
        if statusStr == "开启" {
            status = 1
        } else {
            status = 0
        }
        
        let productsArrayM = NSMutableArray()
        for model in dataArrayM {
            let modelTemp = model as! MCNewMarketingAddGoodsModel
            for productModel in modelTemp.productList {
                let productModelTemp = productModel as! MCNewMarketingEditSKUModel
                
                let dictM = NSMutableDictionary.init()
                dictM.setValue(productModelTemp.goodsId, forKey: "goodsId")
                dictM.setValue(productModelTemp.inventoryId, forKey: "inventoryId")
                dictM.setValue(productModelTemp.inventoryNum, forKey: "inventoryNum")
                dictM.setValue(productModelTemp.productId, forKey: "productId")
                dictM.setValue(productModelTemp.salePrice, forKey: "salePrice")

                productsArrayM.add(dictM)
            }
        }
        
        let para = [
            "activityId"      : activityId,
            "title"           : titleStr,
            "remark"          : remark,
            "startTime"       : startTime,
            "endTime"         : endTime,
            "pickUpStartTime" : pickUpStartTime,
            "pickUpEndTime"   : pickUpEndTime,
            "status"          : status,
            "productList"     : productsArrayM,
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_addActivity, para: para as [String : AnyObject], vc: self,hudSuperView: nil,isHiddenTabbar: true, success: { (response) in

            MCHUD_text(message: "新增社区分销成功", view: self.view, delay: 1.2)
            
            // 更新活动页面数据（全部和社区分销页面）
            MCNotification_post(name: NOTIFICATION_addSocialDistribution, object: nil)
            
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.2, execute: {
                self.navigationController?.popViewController(animated: true)
            })
            
        }, dislike: { (response) in }) { (error) in }
    }
    
    @objc func addGoodsButtonClicked() {
        let vc = MCNewMarketingAddGoodsViewController()
        vc.clousre = { goodsArrayM in
            
            // 和当前页面的数据源对比，相同的goodsId，不加入当前的数据中。
            let arrayM : NSMutableArray = self.dataArrayM.mutableCopy() as! NSMutableArray
            
            // 如果是第一次新增商品
            if arrayM.count == 0 {
                self.dataArrayM = goodsArrayM
            } else {
                // 获取当前商品Id的集合
                let goodsIdArrayM = NSMutableArray()
                for model in arrayM {
                    let modelTemp = model as! MCNewMarketingAddGoodsModel
                    goodsIdArrayM.add(modelTemp.goodsId.intValue)
                }
                
                // 遍历新增的数据
                for model in goodsArrayM {
                    let modelTemp = model as! MCNewMarketingAddGoodsModel
                    
                    let goodsId = modelTemp.goodsId.intValue
                    
                    // 判断是否包含
                    if !goodsIdArrayM.contains(goodsId) {
                        self.dataArrayM.add(modelTemp)
                    }
                }
            }
            self.tableView.reloadData()
        }
        
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
    // MARK: - Network
    func sendNetworking() {
        
        
        let status = dataDict["status"] as? NSNumber ?? 0
        
        
        let title = dataDict["title"] as? String ?? ""
        let remark = dataDict["remark"] as? String ?? ""
        
        let startTime = dataDict["startTime"] as? String ?? ""
        let endTime = dataDict["endTime"] as? String ?? ""
        let pickUpStartTime = dataDict["pickUpStartTime"] as? String ?? ""
        let pickUpEndTime = dataDict["pickUpEndTime"] as? String ?? ""
        let goodsList = dataDict["goodsList"] as? NSArray ?? NSArray()
        
        headView.writeView.titleTextView.textView.text = title
        headView.writeView.detailTextView.textView.text = remark
      
        headView.writeView.titleTextView.limitCountLabel.text = "\(title.count)/\(headView.writeView.titleTextView.limitCount)"
        headView.writeView.detailTextView.limitCountLabel.text = "\(remark.count)/\(headView.writeView.detailTextView.limitCount)"

        
        headView.writeView.detailTextView.textView.becomeFirstResponder()
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
            self.headView.writeView.titleTextView.textView.becomeFirstResponder()
        }
    
        

        
        headView.timeView.activityBeginTimeView.contentButton.setTitle(startTime, for: .normal)
        headView.timeView.activityBeginTimeView.contentButton.isSelected = true
       
        
        headView.timeView.activityEndTimeView.contentButton.setTitle(endTime, for: .normal)
        headView.timeView.activityEndTimeView.contentButton.isSelected = true

        
        headView.timeView.pickUpBeginTimeView.contentButton.setTitle(pickUpStartTime, for: .normal)
        headView.timeView.pickUpBeginTimeView.contentButton.isSelected = true

        headView.timeView.pickUpEndTimeView.contentButton.setTitle(pickUpEndTime, for: .normal)
        headView.timeView.pickUpEndTimeView.contentButton.isSelected = true

        if status.intValue == 0 {
            headView.statusView.statusView.contentButton.setTitle("禁用", for: .normal)
        } else {
            headView.statusView.statusView.contentButton.setTitle("开启", for: .normal)
        }
        headView.statusView.statusView.contentButton.isSelected = true

        
        for dict in goodsList {
            let model = MCNewMarketingAddGoodsModel()
            model.setValuesForKeys(dict as? [String:Any] ?? [:])
            self.dataArrayM.add(model)
        }
        
        
        self.tableView.reloadData()
    }
    
    // MARK: - Method
    func baseSetting() {
        self.title = "新增社区分销"
        self.view.backgroundColor = UIColor.white
        
        navigationItem.rightBarButtonItem = MCSetBarButtonItem_text("完成", target: self, selector: #selector(rightItemClicked))

        
        navigationItem.leftBarButtonItem = MCSetBarButtonItem_image(#imageLiteral(resourceName: "Reuse_back"), target: self, selector: #selector(leftItemClicked),isLeft: true)        
    }
    
    func initUI() {
        view.addSubview(tableView)
        tableView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view)
        }
        
        tableView.tableHeaderView = headView
    }
    
    
    @objc func showPickerViewEvent(sender:UIButton) {
        self.view.endEditing(true)
      
        let tag = sender.tag
        let formatter = DateFormatter.init()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        switch tag {
        case 1000:   // 活动开始时间
            
            // 清空活动开始时间，取货开始结束时间
            headView.timeView.activityEndTimeView.contentButton.isSelected = false
            headView.timeView.activityEndTimeView.contentButton.setTitle("请选择结束时间", for: .normal)
            
            headView.timeView.pickUpBeginTimeView.contentButton.isSelected = false
            headView.timeView.pickUpBeginTimeView.contentButton.setTitle("请选择开始时间", for: .normal)
            
            headView.timeView.pickUpEndTimeView.contentButton.isSelected = false
            headView.timeView.pickUpEndTimeView.contentButton.setTitle("请选择结束时间", for: .normal)
            
            
            let date = Date.init()
            createDatePicerView(type: tag, minDate: date)
        case 1001:   // 活动结束时间
            
            headView.timeView.pickUpBeginTimeView.contentButton.isSelected = false
            headView.timeView.pickUpBeginTimeView.contentButton.setTitle("请选择开始时间", for: .normal)
            
            headView.timeView.pickUpEndTimeView.contentButton.isSelected = false
            headView.timeView.pickUpEndTimeView.contentButton.setTitle("请选择结束时间", for: .normal)
            
            
            let dateStr = headView.timeView.activityBeginTimeView.contentButton.currentTitle ?? ""
            let date = formatter.date(from: dateStr) ?? Date.init()
            let newDate = date.addingTimeInterval(60)
            createDatePicerView(type: tag, minDate: newDate)
            
        case 1002:   // 提货开始时间
            
            headView.timeView.pickUpEndTimeView.contentButton.isSelected = false
            headView.timeView.pickUpEndTimeView.contentButton.setTitle("请选择结束时间", for: .normal)

            
            let dateStr = headView.timeView.activityEndTimeView.contentButton.currentTitle ?? ""
            let date = formatter.date(from: dateStr) ?? Date.init()
            let newDate = date.addingTimeInterval(60)
            createDatePicerView(type: tag, minDate: newDate)
            
        case 1003:   // 提货结束时间
            let dateStr = headView.timeView.pickUpBeginTimeView.contentButton.currentTitle ?? ""
            let date = formatter.date(from: dateStr) ?? Date.init()
            let newDate = date.addingTimeInterval(60)
            createDatePicerView(type: tag, minDate: newDate)
        case 1004:   // 活动状态
            createPicerView(type: tag, array: ["开启","禁用"])
        default:
            break
        }
    }
    
    func createPicerView(type:Int,array:NSArray) {
        let pickerView = MCSinglePickerView()
        pickerView.delegate = self
        pickerView.dataArray = array
        pickerView.type = type
        view.window!.addSubview(pickerView)
        pickerView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view.window!)
        }
    }
    
    func createDatePicerView(type:Int,minDate:Date) {
        let pickerView = MCDatePickerView()
        pickerView.delegate = self
        pickerView.type = type
        pickerView.datePickerView.minimumDate = minDate
        view.window!.addSubview(pickerView)
        pickerView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view.window!)
        }
    }

    
    // MARK: - Setter & Getter
    lazy private var tableView: MCTableView = {
        let tableView = MCTableView.init(frame: CGRect.zero, style: UITableViewStyle.plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.onDrag
        return tableView
    }()
    
    lazy var dataArrayM: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()
    
    lazy var headView: MCNewMarketingHeadView = {
        let view = MCNewMarketingHeadView()
        
        
        view.timeView.activityBeginTimeView.contentButton.tag = 1000
        view.timeView.activityBeginTimeView.contentButton.addTarget(self, action: #selector(showPickerViewEvent(sender:)), for: UIControlEvents.touchUpInside)
        
        view.timeView.activityEndTimeView.contentButton.tag = 1001
        view.timeView.activityEndTimeView.contentButton.addTarget(self, action: #selector(showPickerViewEvent(sender:)), for: UIControlEvents.touchUpInside)
        
        view.timeView.pickUpBeginTimeView.contentButton.tag = 1002
        view.timeView.pickUpBeginTimeView.contentButton.addTarget(self, action: #selector(showPickerViewEvent(sender:)), for: UIControlEvents.touchUpInside)
        
        view.timeView.pickUpEndTimeView.contentButton.tag = 1003
        view.timeView.pickUpEndTimeView.contentButton.addTarget(self, action: #selector(showPickerViewEvent(sender:)), for: UIControlEvents.touchUpInside)
        
        view.statusView.statusView.contentButton.tag = 1004
        view.statusView.statusView.contentButton.addTarget(self, action: #selector(showPickerViewEvent(sender:)), for: UIControlEvents.touchUpInside)
        
        view.addGoodsView.addButton.addTarget(self, action: #selector(addGoodsButtonClicked), for: .touchUpInside)
        
        
        return view
    }()
}

extension MCNewMarketingViewController : UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArrayM.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 104
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = MCNewMarketingCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
        
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        cell.backgroundColor = UIColor.MCGray_light
        
        let model = self.dataArrayM[indexPath.row] as! MCNewMarketingAddGoodsModel
        cell.model = model
        
        
        cell.edit_closure = { cellModel in
            let vc = MCNewMarketingEditSKUViewController()
            vc.model = cellModel
            
            vc.closure = { tempModel in
                self.tableView.reloadData()
            };
            
            MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
        };
        
        cell.delete_closure = { count in
            print(count)
            
            if indexPath.row <= (self.dataArrayM.count - 1) {
                self.dataArrayM.removeObject(at: indexPath.row)
                self.tableView.reloadData()
            }

        }
        return cell
    }
}

extension MCNewMarketingViewController : MCDatePickerViewDelegate {
    func MCDatePickerViewSelectedRow(type: Int, str: String) {
        switch type {
        case 1000:
            headView.timeView.activityBeginTimeView.contentButton.isSelected = true
            headView.timeView.activityBeginTimeView.contentButton.setTitle(str, for: UIControlState.normal)
        case 1001:
            headView.timeView.activityEndTimeView.contentButton.isSelected = true
            headView.timeView.activityEndTimeView.contentButton.setTitle(str, for: UIControlState.normal)
        case 1002:
            headView.timeView.pickUpBeginTimeView.contentButton.isSelected = true
            headView.timeView.pickUpBeginTimeView.contentButton.setTitle(str, for: UIControlState.normal)
        case 1003:
            headView.timeView.pickUpEndTimeView.contentButton.isSelected = true
            headView.timeView.pickUpEndTimeView.contentButton.setTitle(str, for: UIControlState.normal)
        default:
            break
        }
    }
}


extension MCNewMarketingViewController : MCSinglePickerViewDelegate {
   

    func MCSinglePickerViewSelectedRow(type: Int, row: Int, str: String) {
        headView.statusView.statusView.contentButton.isSelected = true
        headView.statusView.statusView.contentButton.setTitle(str, for: UIControlState.normal)
    }
}

